package com.heima.user.web.interceptor;

import com.heima.common.exception.com.heima.common.util.UserThreadLocal;
import com.heima.model.common.user.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.heima.common.exception.com.heima.common.util.UserThreadLocal.USER_THREAD_LOCAL;

@Configuration
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的URL
        String url = request.getRequestURI();
        // URL:除了登录请求外，其他的URL都进行拦截控制
        if (url.indexOf("/login") >=0) {
            return true;
        }
        String userId = request.getHeader("userId");
        if (!StringUtils.isEmpty(userId)){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            USER_THREAD_LOCAL.set(apUser);
            log.warn("拦截器生效{}",apUser);
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        USER_THREAD_LOCAL.remove();
    }
}
